#!coding=utf-8
from xml.etree import ElementTree
from django.http import HttpResponse
from weixin.api import comprocs
from weixin.api.common import getJssdkTicket, getWebAccToken, getWXCustinfo
from weixin.api.sign import Sign
import json

def callback(request):  
    """
    微信的回调信息
    """
    print "weixin in "
    msg = {}
    if request.body == "":
        echoStr = request.GET.get("echostr", "NULL")
        return HttpResponse(echoStr)
    
    xml_elem = ElementTree.fromstring(request.body)
    
    for child in xml_elem:
        for child_2 in child:
            msg[child_2.tag] = child_2.text
        msg[child.tag] = child.text
    
    msgType=msg.get("MsgType")
#     print msgType
    proc_function = getattr(comprocs,"proc_%s"%msgType)
        
    if callable(proc_function):
        return proc_function(msg)
    else:
        return HttpResponse("XML ERROR")
    

def getticket(request):
    url=request.GET.get("url");
    ticket=getJssdkTicket();
    sign = Sign(ticket, url)
    msg=sign.sign();
    print msg
    encodedjson = json.dumps(msg)
    return HttpResponse(encodedjson)
 
def getWXinfo(request):
    code=request.GET.get("code");
    
    openid=request.session.get('openid',False)
    if openid == False:
        openid=getWebAccToken(code)
        request.session['openid']=openid
        
    res = getWXCustinfo(openid)
    return HttpResponse(json.dumps(res))
#  {
#     "subscribe": 1,
#     "openid": "oLVPpjqs2BhvzwPj5A-vTYAX4GLc",
#     "nickname": "刺猬宝宝",
#     "sex": 1,
#     "language": "zh_CN",
#     "city": "深圳",
#     "province": "广东",
#     "country": "中国",
#     "headimgurl": "http://wx.qlogo.cn/mmopen/JcDicrZBlREhnNXZRudod9PmibRkIs5K2f1tUQ7lFjC63pYHaXGxNDgMzjGDEuvzYZbFOqtUXaxSdoZG6iane5ko9H30krIbzGv/0",
#     "subscribe_time": 1386160805
# }
   
        
